package org.example.handle;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MetaObjectHandle implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
    }




    @Override
    public void updateFill(MetaObject metaObject) {
        strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
    }

    public List<Field> getInsertFields(Object originalObject){
        Class<?> aClass = originalObject.getClass();
        Field[] fields = aClass.getDeclaredFields();
        return Arrays.stream(fields).filter(field -> field.isAnnotationPresent(TableField.class))
                .filter(field -> FieldFill.INSERT.equals(field.getAnnotation(TableField.class).fill()))
                .collect(Collectors.toList());
    }
}
